package com.c.ctgproject.wiget.dialog

import android.app.Activity
import android.content.ContentValues
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.provider.MediaStore
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.MediaController
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.fragment.app.DialogFragment
import com.bumptech.glide.Glide
import com.c.ctgproject.R
import com.c.ctgproject.utils.showToast
import kotlinx.android.synthetic.main.item_image_video.*
import kotlinx.coroutines.*
import java.io.OutputStream
import java.util.ArrayList

/**
 *作者:LiBW
 *创建日期: 2021/7/7
 *描述:视频图片 框架
 */
class ShowImgVideoFragment(private val url: String, private val isVideo: Boolean = false) : DialogFragment() {
    private val permissionList = ArrayList<String>()//未申请的权限
    private val mRequestCode = 100//权限申请返回值
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return LayoutInflater.from(context).inflate(R.layout.item_image_video, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBackIv.setOnClickListener {
            dismiss()
        }
        if (isVideo) {
            mTitleTv.text = "视频"
            mPhotoImageLL.visibility = View.GONE
            mVideoRV.visibility = View.VISIBLE
            val uri = Uri.parse(url)
            mVideoView.setMediaController(MediaController(requireContext()))
            mVideoView.setVideoURI(uri)
            //播放完成
            mVideoView.setOnCompletionListener {
                mPlayBTN.visibility=View.VISIBLE
            }
            mPlayBTN.setOnClickListener {
                mPlayBTN.visibility=View.GONE
                mVideoView.start()
            }
            mDownLoadPhoto.visibility=View.GONE
        } else {
            mTitleTv.text = "图片"
            mPhotoImageLL.visibility = View.VISIBLE
            mVideoRV.visibility = View.GONE
            mDownLoadPhoto.visibility=View.VISIBLE
            Glide.with(requireActivity()).load(url).into(mPhotoImageIV)
            mDownLoadPhoto.setOnClickListener {

                   checkPermission()



            }
        }

    }
    private suspend fun savePhoto() { //关键字suspend:在另外的线程允许挂起
        withContext(Dispatchers.IO) {
            //定义线程的范围
            //获取图像的位图资源
            //val holder: PagerPhotoViewHolder = (viewPager2[0] as RecyclerView).findViewHolderForAdapterPosition(viewPager2.currentItem) as PagerPhotoViewHolder
            val bitmap: Bitmap = mPhotoImageIV.drawable.toBitmap() //可以传入图片的大小，默认是显示的图片

            //设置保存地址
            val saveUri: Uri = requireContext().contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                ContentValues()
            ) ?: kotlin.run {
                Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show()
                return@withContext
            }

            //保存图片
            requireContext().contentResolver.openOutputStream(saveUri).use {
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)) { //90%的压缩率，it是输出流
                    //在主线程提示用户
                    MainScope().launch { Toast.makeText(requireContext(), "存储成功", Toast.LENGTH_SHORT).show() }
                } else {
                    MainScope().launch { Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show() }
                }
            }
        }
    }

    //权限检查
    private fun checkPermission() {
        //将需要的权限放入数组
        val permission: Array<String> = arrayOf(
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,

        )
        //清除未申请的权限列表
        permissionList.clear()
        //对权限进行排查将未申请的权限放入List
        for (i in permission.indices) {
            if (context?.let { ContextCompat.checkSelfPermission(it, permission[i]) } != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission[i])
            }
        }

        if (permissionList.size > 0) {//有权限为通过需要申请
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(permission, mRequestCode)
            }
        }else{
            //保存图片到相册
            GlobalScope.launch {
                savePhoto()
            }
        }
    }
    override fun onStart() {
        super.onStart()
        //进入动画
        dialog?.window?.attributes?.windowAnimations = R.style.fromBottomAnimation
        //沉浸状态栏
        val decorView = dialog?.window?.decorView
        val option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        decorView?.systemUiVisibility = option
        // 将状态栏设置成透明色
        dialog?.window?.statusBarColor = Color.TRANSPARENT
        //标题栏文字改为黑色
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            val vis = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or decorView!!.systemUiVisibility
//            decorView.systemUiVisibility = vis
//        }
        //全屏
        dialog?.window?.setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
    }

    //权限回调
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == mRequestCode) {
            checkPermission()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //占全屏没有Margin
        setStyle(STYLE_NORMAL, R.style.CommonCompanyDialog)

    }

}